import os
import time
import threading
import sys

# 定义命名管道的路径
if os.name == 'nt':  # Windows
    pipe_path = r'\\.\pipe\capture_pipe'
    response_pipe_path = r'\\.\pipe\response_pipe'
else:  # Linux / macOS
    pipe_path = '/tmp/capture_pipe'
    response_pipe_path = '/tmp/response_pipe'

# 确保命名管道存在
def create_pipe(path):
    if os.name == 'nt':
        # Windows 不需要手动创建命名管道
        return
    else:
        try:
            os.mkfifo(path)
        except FileExistsError:
            pass  # 如果管道已存在，不做任何事
        except Exception as e:
            print(f"Failed to create named pipe {path}: {e}")
            sys.exit(1)

def capture_photo():
    # 模拟拍照逻辑
    print("Capturing photo...")
    time.sleep(2)  # 模拟拍照耗时
    # 拍照完成后将结果返回
    if os.name == 'nt':
        with open(response_pipe_path, 'w') as response_pipe:
            response_pipe.write("done")
    else:
        with open(response_pipe_path, 'w') as response_pipe:
            response_pipe.write("done")

def camera_process():
    while True:
        with open(pipe_path, 'r') as capture_pipe:
            message = capture_pipe.read(10)  # 读取消息
            if message.strip() == "capture":
                capture_photo()

if __name__ == "__main__":
    create_pipe(pipe_path)  # 创建捕获命名管道
    create_pipe(response_pipe_path)  # 创建反馈命名管道

    print("Camera process started.")
    camera_process()  # 启动相机进程
